from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView
from django_redis import get_redis_connection


from libs.captcha.captcha import captcha
from libs.yuntongxun.sms import CCP
from verifications import contants
from verifications.serializers import RegisterSMScodeSerializer


# 图片验证码
class RegisterImageCodeAPIView(APIView):

    #  #verifications/imagecodes/(?P<image_code_id>.+)/
    def get(self,request,image_code_id):

        # 取得图片和文本信息
        text, image = captcha.generate_captcha()
        # 取得redis库
        redis_connect = get_redis_connection('code')
        # 将取到的东西存储在库中
        redis_connect.setex('image_%s'%image_code_id,contants.IMAGECODE,text)
        # 返回　响应和声明类型
        return HttpResponse(image,content_type='image/jpeg')


# 短信验证
class RegisterSMScodeView(APIView):

    #  GET /verifications/smscodes/(?P<mobile>1[345789]\d{9})/?text=xxxx & image_code_id=xxxx
    def get(self,request,mobile):
        # 因为是ＧＥＴ请求　想要获得参数　query_params　　uuid　　验证码信息　
        data = request.query_params
        # 进行序列化器的校验
        serializer = RegisterSMScodeSerializer(data=data)
        serializer.is_valid(raise_exception=True)

        # 校验完成的数据存入数据库　手机号　
        from random import randint
        # 生成６位随机数　短信验证码
        sms_code = '%06d'%randint(0,999999)
        print(sms_code)

        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile,sms_code)
        # 将短信验证码保存到redis数据库中
        redis_conn = get_redis_connection('code')
        redis_conn.setex('sms_%s'%mobile,contants.ExpirationTime,sms_code)

        return Response({'message:ok'})




